package org.example.auth.service;

import cn.hutool.core.util.ObjectUtil;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.example.common.base.constants.SecurityConstants;
import org.example.common.base.constants.UserConstants;
import org.example.common.base.exception.ServiceException;
import org.example.common.base.util.web.R;
import org.example.common.security.util.SecurityUtils;
import org.example.system.api.entity.LoginUser;
import org.example.system.api.feign.RemoteUserService;
import org.example.system.api.model.SysUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;


/**
 * @version 1.0.0
 * @className: SysLoginService
 * @description:
 * @author: LiJunYi
 * @create: 2022/8/2 15:29
 */
@Component
public class SysLoginService
{
    private static final Logger logger = LoggerFactory.getLogger(SysLoginService.class);

    @Resource
    private RemoteUserService remoteUserService;

    /**
     * 登录
     */
    public LoginUser login(String username, String password)
    {
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(username, password))
        {
            throw new ServiceException("用户/密码必须填写");
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            throw new ServiceException("用户密码不在指定范围");
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            throw new ServiceException("用户名不在指定范围");
        }
        // 查询用户信息
        R<LoginUser> userResult = remoteUserService.getUserInfo(username, SecurityConstants.INNER);

        if (R.FAIL == userResult.getCode())
        {
            throw new ServiceException(userResult.getMsg());
        }

        if (ObjectUtil.isNull(userResult) || ObjectUtil.isNull(userResult.getData()))
        {
            throw new ServiceException("登录用户：" + username + " 不存在");
        }
        LoginUser userInfo = userResult.getData();
        SysUser user = userResult.getData().getSysUser();
        if (!SecurityUtils.matchesPassword(password, user.getPassword()))
        {
            throw new ServiceException("用户不存在/密码错误");
        }
        return userInfo;
    }

    /**
     * 注销
     *
     * @param loginName 登录名
     */
    public void logout(String loginName)
    {
        logger.info("用户{}退出成功",loginName);
    }
}
